package com.neusoft.feature;

import org.junit.Test;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc instanceof的模式匹配
 * @date 2023-01-05
 */
public class InstanceOfFeature {

    /**
     * JDK14以前instanceof的用法
     */
    @Test
    public void test1() {
        Object obj = new String("hello,Java14");
        if (obj instanceof String) {
            String str = (String) obj;
            System.out.println(str.contains("Java"));
        } else {
            System.out.println("非String类型");
        }
    }

    /**
     * JDK 14: 省去了强制类型转换的过程, 直接定义变量赋值
     */
    @Test
    public void test2() {
        Object obj = new String("hello,Java14");

        if (obj instanceof String str) {
            System.out.println(str.contains("Java"));
        } else {
            System.out.println("非String类型");
        }
    }
}

/**
 * 不仅省去了强制类型转换的过程, 直接定义变量赋值，还可以直接返回处理逻辑值
 */
class Monitor {

    private String model;

    private double price;

    public boolean equals1(Object o) {
        if (o instanceof Monitor other) {
            if (model.equals(other.model) && price == other.price) {
                return true;
            }
        }
        return false;
    }


    public boolean equals(Object o) {
        return o instanceof Monitor other && model.equals(other.model) && price == other.price;
    }

}
